﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(1)]
public class FunctionLexer : BaseLexer
{
    public override bool Check()
        => Txt.Contains("FUNCTION ") || Txt.Contains("PROCEDURE ");

    protected override BaseCodeEntity Run()
    {
        var entity = new FunctionCodeEntity();
        var txt = Regex.Replace(Txt, ".*?(FUNCTION|PROCEDURE)", "").Trim();
        var head = Regex.Match(txt, "(.*?)(BEGIN|FUNCTION|PROCEDURE)").Result("$1").Trim();
        if (head.Contains("/*") && head.Contains("*/"))
        {
            var mats = Regex.Matches(txt, "/\\*.*?\\*/");
            var sub = new List<string>();
            foreach (Match mat in mats.Cast<Match>())
            {
                sub.Add(mat.Value);
                head= head.Replace(mat.Value, "");
            }
            entity.Comments = sub;
        }
        entity.Name = Regex.Match(head, "(.*?)(\\s[IA]S|\\()").Result("$1").Trim();
        var parmas = Regex.Match(head, "\\(.*?[\\s)][IA]S").Value;
        if (!string.IsNullOrEmpty(parmas))
        {
            parmas= parmas[..^2].Trim();
            ListParams(parmas, entity.Params);
        }
        var dec = Regex.Match(head, "[\\s)][IA]S(.*)").Result("$1").Replace("÷", "").Trim();
        if (!string.IsNullOrEmpty(dec))
        {
            var arr = dec.TrimSplit(';');
            entity.Declare = [];
            foreach (var item in arr)
            {
                entity.Declare.Add(SqlFactory.Create(item).Execute());
            }
        }
        if (txt.Contains("RETURN "))
        {
            var res = Regex.Match(txt, "RETURN(.*?)(IS|AS)").Result("$1");
            entity.Return = OracleHelp.RealType(res);
        }
        txt = txt.Replace(head, "").Trim();
        if (txt.StartsWith("BEGIN"))
        {
            entity.Body.Add(SqlFactory.Create(txt).Execute());
        }
        else
        {

        }
        return entity;
    }
}
